#  spatial.lag2.r
#  W is a NT weights matrix sorted accordingly (by year and country)
#  y is a vector from the main data ([data]$y) 
#  note: W and y must have the same ending year

spatial.lag <- function(period, path, filenames, data, yvar) {
	Wy <- as.vector(rep(NA, nrow(data)))
	for (i in period){
		# the W matrix
		W <- as.matrix(read.csv(paste(path, filenames, i, ".csv", sep=""), sep=",", header=T))
		diag(W) <- 0
		W[W<0] <- 0 	               # replaces <0 with 0s
		W[is.na(W)] <- 0
		# row-standardize the "www" matrix.
		n <- nrow(W)
		for(a in 1:n){
			ifelse(sum(W[a,])==0, W[a,]<-0,	W[a,] <- W[a,]/sum(W[a,]))
			}
		# the Y variable
		y.year  <- data[data$year==i, yvar]
		y.noNA  <- ifelse(is.na(y.year), 0, y.year)
		Wy      <- ifelse(data$year==i, W%*%y.noNA, Wy)		   
		}
	Wy <- ifelse(Wy==0, NA, Wy)	
	}